<!DOCTYPE html>
<html>

	<head>
		<title>网工二聊天室</title>
		<meta charset="utf-8">

		<!--<link rel="stylesheet" href="css/reset.css" />
		<link rel="stylesheet" href="css/bootstrap.css" />
		<link rel="stylesheet" href="css/app.css" />-->
		<link rel="stylesheet" href="/reset.css" />
		<link rel="stylesheet" href="/bootstrap.css" />
		<link rel="stylesheet" href="/app.css" />
		<style type="text/css">
			body {
				padding-bottom: 100px;
			}
			
			#title {
				width: 50%;
				height: 63px;
				line-height: 63px;
				text-align: center;
				font-size: 20px;
				font-weight: bold;
				border: 3px solid pink;
				margin: 0 auto;
			}
			
			.biaoqing {
				position: absolute;
				right: 134px;
				bottom: 70px;
				width: 300px;
				height: 200px;
				border: 1px solid pink;
				background-color: antiquewhite;
				display: none;
				flex-wrap: wrap;
				text-align: center;
				align-items: flex-start;
				justify-content: space-between;
			}
			
			.biaoqing span {
				flex: 15%;
				height: 50px;
				border: 1px solid red;
				line-height: 50px;
				cursor: pointer;
			}
			
			.liuxingyu {
				position: absolute;
				right: 172px;
				bottom: 70px;
				width: 150px;
				height: 300px;
				border: 1px solid pink;
				background-color: antiquewhite;
				text-align: center;
				display: none;
			}
			
			.liuxingyu span {
				display: block;
				width: 100%;
				height: 42px;
				border: 1px solid red;
				line-height: 50px;
				cursor: pointer;
			}
			
			.upload {
				width: 100px;
				height: 100px;
			}
			
			.wrapper {
				height: 101%;
			}
			
			.wrapper .action {
				overflow: unset;
			}
			
			#upload {
				position: absolute;
				bottom: 18px;
				left: 160px;
			}
			
			#img {
				width: 50px;
				height: 50px;
			}
			
			.people {
				position: absolute;
				left: 0;
				top: 100px;
				width: 10%;
				height: 500px;
				background-color: skyblue;
			}
			
			.peoTitle {
				width: 100%;
				height: 50px;
				background-color: blueviolet;
				font-size: 20px;
				line-height: 50px;
				text-align: center;
			}
			
			.memberDetail {
				background-color: orange;
				overflow: auto;
				height: 450px;
			}
			
			.memberDetail li {
				height: 50px;
				line-height: 50px;
				text-align: center;
				font-size: 16px;
				list-style: none;
			}
		</style>
	</head>

	<body>
		<div class="content" id="title">
			聊天室
		</div>
		<!--在线人数系统：-->
		<div class="people">
			<div class="peoTitle">
				在线人数：<span id="sumPeople">0</span>
			</div>
			<ul class="memberDetail">

			</ul>

		</div>

		<div class="wrapper">
			<div class="content" id="chat">
				<ul id="chat_conatiner">
				</ul>

			</div>
			<div class="action" style="position: relative">
				<textarea rows="2" cols="10" maxlength="30"></textarea>
				<button class="btn btn-success" id="clear">清屏</button>
				<button class="btn btn-success" id="send">发送</button>
				<button class="btn btn-success" id="biaoqing">表情</button>
				<button class="btn btn-error" id="liuxingyu">流行语</button>
				<div class="liuxingyu">
					<span>奥力给</span>
					<span>nmsl</span>
					<span>你说你🐎呢</span>
					<span>雨女无瓜👩</span>
					<span>好嗨哟😲</span>
					<span>道路千万条，安全第一条</span>
					<span>不要跟我逼逼赖赖</span>
				</div>
				<div class="biaoqing">
					<span>😂</span>
					<span>😘</span>
					<span>😍</span>
					<span>😊</span>
					<span>😁</span>
					<span>😭</span>
					<span>😜</span>
					<span>😝</span>
					<span>😱</span>
					<span>😄</span>
					<span>😡</span>
					<span>🙃</span>
					<span>😡</span>
					<span>🐷</span>
					<span>🐎</span>
					<span>🐂🍺</span>
					<span>🥂</span>
					<span>💪</span>
					<button class="btn1"><</button>
					<button class="btn2">></button>
				</div>

				<div class="form-group">
					<label>File input:</label>
					<input type="file" name="files" id="file">
					<p id="result"></p>
					<img id="img" src="">
				</div>
				<button id="upload" class="btn btn-default">发送文件(支持图片，视频)</button>

			</div>
		</div>
		<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
		<script type="text/javascript" src="/socket.io.js"></script>
		<!--<script type="text/javascript" src="js/socket.io.js"></script>-->
		<script type="text/javascript">
			var ws = io.connect('http://192.168.0.101:10005');
			var sendMsg = function(msg) {
				ws.emit('send.message', msg);
			}

			//在线人数
			var totalMember = 0
			//用户数组
			var peopleList

			var addMessage = function(from, msg) {
				if(from == "在线人数") {
					totalMember = msg
					console.log(totalMember)
					document.querySelector("#sumPeople").innerHTML = totalMember
					return
				}

				if(from == "用户数组") {
					peopleList = msg
					console.log(peopleList)
					document.querySelector('.memberDetail').innerHTML = " "
					for(var i = 0; i < peopleList.length; i++) {
						var li = document.createElement('li');
						li.innerHTML = peopleList[i].name
						document.querySelector('.memberDetail').appendChild(li);

					}

					return
				}

				if(from == "龙某人") {
					var li = document.createElement('li');
					li.innerHTML = '<span style="color: skyblue;">' + from + "(房管)" + '</span>' + ' : ' + msg;
					document.querySelector('#chat_conatiner').appendChild(li);

					updata()

					return
				}

				if(from == "系统") {
					var li = document.createElement('li');
					li.innerHTML = '<span style="color: red;">' + from + '</span>' + ' : ' + msg;
					document.querySelector('#chat_conatiner').appendChild(li);

					updata()

					return
				}
				var reg1 = /.png/
				var reg2 = /.jpg/
				var reg3 = /.jpeg/
				var reg4 = /.gif/
				if(reg1.test(msg) || reg2.test(msg) || reg3.test(msg) || reg4.test(msg)) {
					var li = document.createElement('li');
					li.innerHTML = '<span>' + from + '</span>' + ' : ' + '<img src="' + msg + '"/>';
					document.querySelector('#chat_conatiner').appendChild(li);
					updata()
					return
				}
				var reg5 = /(.mp4)|(.MP4)/
				var reg6 = /(.ogg)/
				var reg7 = /(.WebM)/
				if(reg5.test(msg) || reg6.test(msg) || reg7.test(msg)) {
					//video标签
					var li = document.createElement('li');
					li.innerHTML = '<span >' + from + '</span>' + ' : ' + `<video width="320" height="240" controls >
    <source src="${msg}" type="video/mp4">
    <source src="${msg}" type="video/ogg">
    <source src="${msg}" type="video/webm">
           看不到视频,说明您的浏览器版本太低，请使用高版本的
       </video>`
					document.querySelector('#chat_conatiner').appendChild(li);
					updata()

					return
				}

				var li = document.createElement('li');
				li.innerHTML = '<span>' + from + '</span>' + ' : ' + msg;
				document.querySelector('#chat_conatiner').appendChild(li);
				updata()
			}

			//监听消息的刷屏,3秒内超过5条信息则不允许发送，提示消息太快
			var start = new Date()
			var total = 0
			var Name = ""
			var send = function() {
				var ele_msg = document.querySelector('textarea');
				var msg = ele_msg.value.replace('\r\n', '').trim();
				console.log(msg);
				if(!msg) return;
				sendMsg(msg);
				// 添加消息到自己的内容区
				addMessage('你', msg);
				ele_msg.value = '';
			}

			ws.on('connect', function() {
				var nickname = window.prompt('输入你的昵称!');
				while(!nickname) {
					nickname = window.prompt('昵称不能为空，请重新输入!')
				}
				Name = nickname
				console.log("告诉服务器，我加入进来了")
				ws.emit('join', nickname);
			});

			// 昵称有重复
			ws.on('nickname', function() {
				var nickname = window.prompt('昵称有重复，请重新输入!');
				while(!nickname) {
					nickname = window.prompt('昵称不能为空，请重新输入!')
				}
				Name = nickname
				ws.emit('join', nickname);
			});

			ws.on('send.message', function(from, msg) {
				addMessage(from, msg);
			});

			ws.on('announcement', function(from, msg) {
				addMessage(from, msg);
			});

			document.querySelector('textarea').addEventListener('keypress', function(event) {
				if(event.which == 13) {
					if(!isOk()) {
						window.alert("消息发送发送太快了（禁止刷屏）")
						return
					}
					send();
					total++
				}
			});
			document.querySelector('textarea').addEventListener('keydown', function(event) {
				if(event.which == 13) {
					if(!isOk()) {
						window.alert("消息发送发送太快了（禁止刷屏）")
						return
					}
					send();
					total++
				}
			});
			document.querySelector('#send').addEventListener('click', function() {
				if(!isOk()) {
					window.alert("消息发送发送太快了（禁止刷屏）")
					return
				}
				send();
				total++
			});

			document.querySelector('#clear').addEventListener('click', function() {
				document.querySelector('#chat_conatiner').innerHTML = '';
			});

			//判断是否符合刷屏
			function isOk() {
				if(total > 5) return false
				else return true
			}

			setInterval(function() {
				total = 0
			}, 5000)

			//表情包的开关
			var flag = false
			document.querySelector('#biaoqing').onclick = function() {
				var biaoqing = document.querySelector('.biaoqing')
				if(flag) {
					biaoqing.style.display = "none"
					flag = false
				} else {
					biaoqing.style.display = "flex"
					flag = true
				}

				//打开表情包列表就给每一个表情包绑定点击事件
				var spans = document.querySelectorAll('.biaoqing span')
				for(var i = 0; i < spans.length; i++) {
					spans[i].onclick = function() {
						var tex = document.querySelector('textarea')
						//              	    var start=tex.value
						var end = this.innerHTML
						//              	    var str=start+end
						insertText(tex, end)
						//              	    tex.value=str
						var biaoqing = document.querySelector('.biaoqing')
						biaoqing.style.display = "none"
						flag = false
					}
				}
			}

			//流行语开关
			var flag1 = false
			document.querySelector('#liuxingyu').onclick = function() {
				var biaoqing = document.querySelector('.liuxingyu')
				if(flag1) {
					biaoqing.style.display = "none"
					flag1 = false
				} else {
					biaoqing.style.display = "block"
					flag1 = true
				}

				//打开表情包列表就给每一个表情包绑定点击事件
				var spans = document.querySelectorAll('.liuxingyu span')
				for(var i = 0; i < spans.length; i++) {
					spans[i].onclick = function() {
						var tex = document.querySelector('textarea')
						//              	    var start=tex.value
						var end = this.innerHTML
						//              	    var str=start+end
						insertText(tex, end)
						//              	    tex.value=str
						var biaoqing = document.querySelector('.liuxingyu')
						biaoqing.style.display = "none"
						flag1 = false
					}
				}
			}

			//失去焦点，表情包隐藏
			//           document.querySelector('#biaoqing').onblur=function(){
			//           	var biaoqing=document.querySelector('.biaoqing')
			//           		biaoqing.style.display="none"
			//          		flag=false
			//           }

			//在光标后添加表情包 
			function insertText(obj, str) {
				if(document.selection) {
					var sel = document.selection.createRange();
					sel.text = str;
				} else if(typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
					var startPos = obj.selectionStart,
						endPos = obj.selectionEnd,
						cursorPos = startPos,
						tmpStr = obj.value;
					obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
					cursorPos += str.length;
					obj.selectionStart = obj.selectionEnd = cursorPos;
				} else {
					obj.value += str;
				}
			}

			//图片的上传和预览
			//         document.querySelector("#upload").onchange = function() {
			//	  var files = this.files;
			//	  document.querySelector("img").src = window.URL.createObjectURL(files[0]);
			//	  files.slice()
			//	}

			//上传图片的业务逻辑函数
			function uploadFile() {
				//上传图片的input
				var file = document.getElementById("file")
				//因为准备用post提交，又因为图片的内容比较大，所以我们选择使用formdata来承载数据
				//创建formdata对象
				var formData = new FormData();
				//给formdata对象中放入数据(键值对的方式)
				formData.append('file', file.files[0]);
				//提交请求
				$.ajax({
					url: 'http://192.168.0.101:10005/uploads', //请求路径
					type: 'POST',
					data: formData,
					contentType: false, //为了让浏览器根据传入的formdata来判断contentType
					processData: false, //同上
					success: function(data) {
						if(200 === data.code) {
							$('#result').html("上传成功！");
							$('#img').attr('src', data.data);
							console.log(data)
							console.log(data.data)
							//上传成功就向每一个连接者发送一个服务器中返回来的url，确保都能看到这张图片或视频
							ws.emit('send.message', data.data);
							var reg1 = /(.mp4)|(.MP4)/
							var reg2 = /(.ogg)/
							var reg3 = /(.WebM)/
							if(reg1.test(data.data) || reg2.test(data.data) || reg3.test(data.data)) {
								//video标签
								var li = document.createElement('li');
								li.innerHTML = '<span >' + Name + '</span>' + ' : ' + `<video width="320" height="240" controls >
    <source src="${data.data}" type="video/mp4">
    <source src="${data.data}" type="video/ogg">
    <source src="${data.data}" type="video/webm">
           看不到视频,说明您的浏览器版本太低，请使用高版本的
       </video>`
								document.querySelector('#chat_conatiner').appendChild(li);
								updata()

								return
							}
							var li = document.createElement('li');
							li.innerHTML = '<span >' + Name + '</span>' + ' : ' + '<img src="' + data.data + '"/>';
							document.querySelector('#chat_conatiner').appendChild(li);
							updata()

						} else {
							$('#result').html("上传失败！");
						}
						console.log(2)
					},
					error: function() {
						$("#result").html("与服务器通信发生错误");
					}
				});
				console.log(1)
			}

			//给按钮添加点击事件
			function postPage() {
				//上传按钮
				var uploada = document.getElementById('upload');
				uploada.addEventListener("click", function() {
					if(!isOk()) {
						window.alert("消息发送发送太快了（禁止刷屏）")
						return
					}
					uploadFile();
					total++
				}, false);
			}
			window.onload = function() {
				postPage();
			}

			function updata() {
				setTimeout(function() {
					// 设置内容区的滚动条到底部
					document.querySelector('#chat').scrollTop = document.querySelector('#chat').scrollHeight;

					// 并设置焦点
					document.querySelector('textarea').focus();
				}, 100)
			}
		</script>
	</body>

</html>